package com.waps;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

/**
* Created by IntelliJ IDEA.
* User: guang
* Date: 11-3-10
* Time: 下午7:09
* To change this template use File | Settings | File Templates.
*/
public class AppURLConnection
{
    private static final String URL_CONNECTION = "AppURLConnection";


    public AppURLConnection()
    {

    }


    /**
     * 执行联网的请求
     * @param url					url地址
     * @param params				url参数
     * @return 						服务器返回内容.
     */
    public String connectToURL(String url, String params)
    {
        String httpResponse = null;

        try
        {
            String requestURL = url + params;

            // 过滤所有空格.
            requestURL = requestURL.replaceAll(" ", "%20");

            AppLog.i(URL_CONNECTION, "baseURL: " + url);
            AppLog.i(URL_CONNECTION, "requestURL: " + requestURL);

            HttpGet http = new HttpGet(requestURL);

            // 创建一个HttpParams 对象.
            HttpParams httpParameters = new BasicHttpParams();

            // 超时时间
            HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);

            // 等待数据返回时间.
            HttpConnectionParams.setSoTimeout(httpParameters, 30000);

            // 创建一个连接.
            HttpClient client = new DefaultHttpClient(httpParameters);

            HttpResponse response = client.execute(http);
            HttpEntity entity = response.getEntity();

            httpResponse = EntityUtils.toString(entity);

            AppLog.i(URL_CONNECTION, "--------------------");
            AppLog.i(URL_CONNECTION, "response status: " + response.getStatusLine().getStatusCode());
            AppLog.i(URL_CONNECTION, "response size: " + httpResponse.length());
            AppLog.i(URL_CONNECTION, "response: ");
            AppLog.i(URL_CONNECTION, "" + httpResponse);
            AppLog.i(URL_CONNECTION, "--------------------");
        }
        catch (Exception e)
        {
            AppLog.e(URL_CONNECTION, "Exception: " + e.toString());
        }

        return httpResponse;
    }
}
